package com.zeng.ssm.service.support.plugin;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.Map;

/**
 * 打印查询结果
 *
 * @author zengwanlin
 * @date 2022-01-27T15:10
 */
@Intercepts(
        value = @Signature(
                type = Executor.class,
                method = "query",
                args = {
                        MappedStatement.class,
                        Object.class,
                        RowBounds.class,
                        ResultHandler.class
                }
        )
)
public class PrintPlugin implements Interceptor {

    private final Logger logger = LoggerFactory.getLogger(PrintPlugin.class);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 执行目标方法
        Object object = invocation.proceed();

        // 打印结果日志，避免抛错
        try {
            if (object instanceof Collection) {
                Collection collection = (Collection) object;
                collection.forEach(obj -> {
                    logInfo(obj);
                });
            } else if (object instanceof Map) {
                Map map = (Map) object;
                logInfo(map);
            } else {
                logInfo(object);
            }
        } catch (Throwable t) {
            // ignore
        }

        return object;
    }

    private void logInfo(Object object) {
        if (object == null) {
            logger.info("null");
        } else {
            logger.info(object.toString());
        }
    }

}
